package com.wingsboat;

import java.util.HashMap;

/**
 * @author wangzhong
 * @description: 最长子字符串的长度
 * 给你一个字符串 s，字符串 s 首尾相连成一个环形，请你在环中找出 'l'、'o'、'x' 字符都恰好出现了偶数次最长子字符串的长度。
 * @date 2024/7/23 11:21
 */
public class Test18 {
    public static void main(String[] args){
        String str = "loloboa";
        int maxLength = 0;
        for(int i=0;i<str.length();i++){
            str = str.substring(1) + str.charAt(0);
            maxLength = Math.max(maxLength,getMaxLength(str));
        }
        System.out.println(maxLength);
    }

    public static int getMaxLength(String str){
        int maxLength = 0;
        HashMap<Character,Integer>[] charMaps = new HashMap[str.length()];
        for(int i = 0;i<str.length();i++){
            HashMap<Character,Integer> map = new HashMap<>();
            if(i==0){
                map.put('l',0);
                map.put('x',0);
                map.put('o',0);
            }else{
                map.put('l',charMaps[i - 1].get('l'));
                map.put('x',charMaps[i - 1].get('x'));
                map.put('o',charMaps[i - 1].get('o'));
            }
            if(str.charAt(i) == 'l' || str.charAt(i) == 'o' || str.charAt(i) == 'x'){
                int c = 1 + map.get(str.charAt(i));
                map.put(str.charAt(i), c);
            }
            charMaps[i] =map;
        }
        for(int r=0;r<str.length();r++){
            for(int l=0;l<=r;l++){
                if(check(l,r,charMaps)){
                    maxLength = Math.max(maxLength,r-l+1);
                }
            }
        }
        return maxLength;
    }

    public static boolean check(int l,int r,HashMap<Character,Integer>[] charMaps){
        if(l==0){
            int charL = charMaps[r].get(new Character('l'));
            if(charL%2==0){
                int charO =  charMaps[r].get(new Character('o'));
                if(charO%2==0){
                    int charX = charMaps[r].get(new Character('x'));
                    if(charX%2==0) return true;
                }
            }
            return false;
        }else{
            int charL = charMaps[r].get(new Character('l')) - charMaps[l-1].get(new Character('l'));
            if(charL%2==0){
                int charO =  charMaps[r].get(new Character('o'))-charMaps[l-1].get(new Character('o'));
                if(charO%2==0){
                    int charX = charMaps[r].get(new Character('x'))-charMaps[l-1].get(new Character('x'));
                    if(charX%2==0) return true;
                }
            }
            return false;
        }
    }

}
